package com.jn.rxjavaretrofit_demo0802;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

public class WeatherActivity extends AppCompatActivity {
    private ApiService apiService;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    private TextView tvCityName, tvCurrentCondition, tvCurrentTemperature, tvTips;
    private ImageView ivWeatherIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        initViews();
        apiService = RetrofitClient.getClient("https://api.oioweb.cn/api/").create(ApiService.class);
        fetchWeatherData("郑州市");
    }

    private void initViews() {
        tvCityName = findViewById(R.id.tvCityName);
        tvCurrentCondition = findViewById(R.id.tvCurrentCondition);
        tvCurrentTemperature = findViewById(R.id.tvCurrentTemperature);
        tvTips = findViewById(R.id.tvTips);
        ivWeatherIcon = findViewById(R.id.ivWeatherIcon);
    }

    private void fetchWeatherData(String cityName) {
        compositeDisposable.add(apiService.getWeather(cityName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::showWeatherData, this::handleError));
    }

    private void showWeatherData(WeatherResponse weatherResponse) {
        WeatherResponse.Result result = weatherResponse.getResult();
        tvCityName.setText(result.getCity_name());
        tvCurrentCondition.setText(result.getCurrent_condition());
        tvCurrentTemperature.setText(String.valueOf(result.getCurrent_temperature()));
        tvTips.setText(result.getTips());

        // Load weather icon using Glide
        Glide.with(this)
                .load("https://api.oioweb.cn/api/weather/icon/" + result.getForecast_list().get(0).getWeather_icon_id() + ".png")
                .into(ivWeatherIcon);
    }

    private void handleError(Throwable throwable) {
        throwable.printStackTrace();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }
}